//
//  BAAlbumScrollLayout.m
//  BabyAlbum
//
//  Created by master on 17/2/14.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAAlbumScrollLayout.h"
CGFloat ActiveDistance = 400; //垂直缩放除以系数
CGFloat ScaleFactor = 0.25;    //缩放系数  越大缩放越大

//@interface BAAlbumScrollLayout ()
//{
//    CGRect _forceBounds;
//}
//
//@end

@implementation BAAlbumScrollLayout

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
    CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.width, self.collectionView.height);
    // 目标区域中包含的cell
    NSArray<UICollectionViewLayoutAttributes *> *attriArray = [super layoutAttributesForElementsInRect:targetRect];
    // collectionView落在屏幕中点的x坐标
    CGFloat horizontalCenterX = proposedContentOffset.x + (self.collectionView.width / 2);
    CGFloat offsetAdjustment = MAXFLOAT;
    for (UICollectionViewLayoutAttributes * layoutAttributes in attriArray) {
        CGFloat itemHorizontalCenterX = layoutAttributes.center.x;
        if(fabs(itemHorizontalCenterX - horizontalCenterX) < fabs(offsetAdjustment)) {
            // 找出离中心点最近的
            offsetAdjustment = itemHorizontalCenterX - horizontalCenterX;
        }
    }
     //返回collectionView最终停留的位置
    return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}


- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
//    if(CGRectIsEmpty(_forceBounds)) {
//        _forceBounds = self.collectionView.bounds;
//    } else {
//        self.collectionView.bounds = _forceBounds;
//    }
//    NSLog(@"%@",NSStringFromCGRect(self.collectionView.bounds));

    NSArray *array = [super layoutAttributesForElementsInRect:rect];
//    NSLog(@"%@",NSStringFromCGSize(self.collectionView.contentSize));
//    NSLog(@"%@,%f,%f",NSStringFromCGRect(rect),self.collectionView.contentOffset.x,self.collectionView.contentOffset.y);
    CGRect visibleRect = CGRectMake(self.collectionView.contentOffset.x, self.collectionView.contentOffset.y, self.collectionView.width, self.collectionView.height);
    for (UICollectionViewLayoutAttributes * attributes in array) {
        CGFloat distance = CGRectGetMidX(visibleRect) - attributes.center.x;
        CGFloat normalizedDistance = fabs(distance/ActiveDistance);
        CGFloat zoom = 1 - ScaleFactor * normalizedDistance;
        attributes.transform3D = CATransform3DMakeScale(1.0, zoom, 1.0);
        attributes.zIndex = 1;

        //            let alpha = 1 - normalizedDistance
        //            attributes.alpha = alpha
    }
    return array;
}

- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    //滑动放大缩小  需要实时刷新layout
    return YES;
}

@end
